var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var reload = true;
var page = 2;
var hasMore = true;
var loadingMore = false;

var SDKVersion = '';
var status = true;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: app.globalData.imgDomain,

    classlysData: '',

    zxsData: [],
    hasData: true,
    util: util,
    uid: 0,
    token: '',
    openid: '',
    canEdit: 0,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    shouqian_phone: '',
    colorSet: '',
    wz_item_img_w_1: 300,

    hide_commentview: true,

    paimingResult: [],  //全部排名
    paimingData: [],  //当前页排名

    meKey:'',
    meArray:[],
    
    
    guanxi: [],
    guanxiIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tc = app.get_tc();
    var titlename = tc == 1 ? '商圈' : '商圈';
    wx.setNavigationBarTitle({
      title: titlename,
    });
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })

    page = 2;
    hasMore = true;
    loadingMore = false;

    var that = this;
    that.getRelationships();

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('car-commerce/car-commerce', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })

    reload = true;
    //当前登录用户信息
    app.LoginUserInfo(function (res) {
      var authFail = res == -1;//用户拒绝授权
      if (!authFail) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid
        });
      }

    });
    //获取关于等信息
    app.getAllAbout('shouqian', function (res) {
      that.setData({
        shouqian_phone: res
      })
    });
 

    that.getFriendsHelp();
  },


  //好友排名表
  getFriendsHelp: function(){
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "applicationform",
      uid: that.data.uid,
      orgid: util.orgid,
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("好友排名表:", result);

        result.sort(that.compare('count'));
        
        that.setData({
          paimingResult: result,
          paimingData: result.slice(0, 20)
        });
        
        var meKey= 1;
        var meArray = [];
        for (var index = 0; index < result.length; index++) {
          
          if(that.data.uid == result[index]['uid']){
            meKey = index+1;
            meArray.push(result[index]);
          }
        }
        that.setData({
          meKey: meKey,
          meArray: meArray
        })
        wx.hideLoading();
         console.log("wo de paiming:", meArray);
         console.log("wo de meKey:", meKey);
      }
    });
  },


  //点击图片放大
  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  compare:function (property){
      return function(a,b){
          var value1 = a[property];
          var value2 = b[property];
          return value2 - value1;
      }
  },


   loadMore: function (e) {

    if (hasMore && !loadingMore) {
      
      
      page++;
      this.loadpaiming(page);
    } else {
      console.log("没有更多了");
    }
  },


 loadpaiming:function(page){
   var that = this;
   console.log(page);
   console.log(that.data.paimingData);
   console.log(that.data.paimingResult);
   
    that.setData({
        paimingData: that.data.paimingResult.slice(0, page*10)
    });
        
    if(that.data.paimingData.length == that.data.paimingResult.length){
      loadingMore = true;
    }
  
    
    console.log(that.data.paimingData);
 },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },
  //页面分享
  onShareAppMessage: function (res) {
    
    var that = this;
    if (res.from === 'menu') { //页面右上角分享
      var inviteuid = that.data.uid ? that.data.uid : '';

    }else{ //页面按钮分享
      var inviteuid = res.target.id;
  
      // console.log(res);
    }


    var result = that.data.paimingResult;
    for (var index = 0; index < result.length; index++) {
          if(inviteuid == result[index]['uid']){
            var key = index+1;
            // var result = JSON.stringify(result[index]);
            var result = result[index];
          }
        }
      
      var array = {};
      array['key'] = key;
      array['inviteuid'] = inviteuid;
      array['result'] = result;
      
      var option = JSON.stringify(array);
      console.log(array);
      console.log(option);

    return {
      title: '为TA点赞，获取更多关注',
      path: '/pages/music_circle_share/music_circle_share?&array=' + option
    };
  },

  // 获取关系数组
  getRelationships: function () {
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "goodstype",
      "tc": that.data.tc
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("result::::", result);
        for(var i=0;i<result.length;i++){

          console.log("result[i].title:", result[i].title);
          if (result[i].title == "職業分類" || result[i].title == "職業" || result[i].title == "其他"){
            let arr = result[i].child;
            let guanxi =[];
            
            for (var j = 0; j < arr.length; j++){
              let itemObj = {};
              itemObj.id = arr[j]['goods_id']
              itemObj.title=arr[j]['title']
              guanxi.push(itemObj);
            }
            guanxi.sort(function (a, b) {
              return a.id - b.id;
            });
            that.setData({
              guanxi: guanxi
            });
            console.log("关系数组:", guanxi);
          }
        }
        
        
      }
    });
  },

  //关系选项改变值
  guanxiPickerChange: function (e) {//选项改变触发事件
    console.log("选中了:", e.currentTarget.dataset.typeid);
    var that= this;
    // this.setData({
    //   guanxiIndex: e.detail.value
    // })

    var privatekey = utilMd5.hexMD5(that.data.uid + 'updateUserType' + that.data.token);
    var params = {
      ac: "updateUserType",
      uid: that.data.uid,
      classification: e.detail.value,
      userId: e.currentTarget.dataset.id,
      privatekey: privatekey
    };


    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("提交信息：", responseData);
        if (responseData.data.res == false) {
          wx.showModal({
            title: '提示',
            content: responseData.data.msg,
            showCancel: false,
          })
        } else {
          var contentsucess = this.data.tc == 1 ? '保存成功' : '保存成功';
           wx.showModal({
            title: '提示',
            content: contentsucess,
            showCancel: false,
          
          });
          that.getFriendsHelp();
        }

      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });

    
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
  hide:function(e){
    console.log("hide选中了:", e);
    var that = this;    
    console.log("hide:", e.detail.value);
    // console.log("hide:", e.currentTarget.dataset.show);
    console.log("hide:", e.currentTarget.dataset.id);
    var privatekey = utilMd5.hexMD5(that.data.uid + 'updateUserShow' + that.data.token);
    var params = {
      ac: "updateUserShow",
      uid: that.data.uid,
      show: e.detail.value==true?0:1,
      // show: e.currentTarget.dataset.show,
      userId: e.currentTarget.dataset.id,
      privatekey: privatekey
    };


    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("提交信息：", responseData);
        if (responseData.data.res == false) {
          wx.showModal({
            title: '提示',
            content: responseData.data.msg,
            showCancel: false,
          })
        } else {
          // var contentsucess = that.data.tc == 1 ? '保存成功' : '保存成功';
          // wx.showModal({
          //   title: '提示',
          //   content: contentsucess,
          //   showCancel: false,

          // });
          that.getFriendsHelp();
        }

      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });

  }

})